package com.itheima.service.impl;

import com.itheima.dao.UserMemberDao;
import com.itheima.dao.UserOrderDao;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderDTO;
import com.itheima.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private UserOrderDao userOrderDao;

    @Autowired
    private UserMemberDao userMemberDao;

    /**
     * 根据id查询预约信息
     * @param id
     * @return
     */
    @Override
    public Order findById(Integer id) {

        return userOrderDao.findById(id);
    }

    /**
     * 体检预约
     * @param orderDTO
     * @return
     */
    @Override
    @Transactional
    public Integer submitOrder(OrderDTO orderDTO) {
        // 预约用户不是会员，则自动注册为会员(根据身份证id，判断是否注册)
        Member member = userMemberDao.findByPhoneNumber(orderDTO.getTelephone());
        Order order = new Order();

        // 有可能是帮别的用户预约
        if (member == null){
            Member member1 = new Member();
            member1.setIdCard(orderDTO.getIdCard());
            member1.setName(orderDTO.getName());
            member1.setSex(orderDTO.getSex());
            member1.setPhoneNumber(orderDTO.getTelephone());
            member1.setRegTime(new Date());

            userMemberDao.add(member1);
            order.setMemberId(member1.getId());
        }else {
            order.setMemberId(member.getId());
        }

        order.setOrderDate(orderDTO.getOrderDate());
        order.setSetmealId(orderDTO.getSetmealId());
        // 通过小程序方式进行预约，预约方式：微信预约
        order.setOrderType(Order.ORDERTYPE_WEIXIN);
        order.setOrderStatus(Order.ORDERSTATUS_NO);

        Integer recordCount = userOrderDao.add(order);

        return recordCount;
    }
}
